"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
exports.getAttach = getAttach;

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _react = require("react");

var _reactDom = require("react-dom");

var isNoSSR = function isNoSSR() {
  return typeof document !== 'undefined';
};

function getAttach(attach) {
  var parent;

  if (typeof attach === 'string' && attach && isNoSSR()) {
    parent = document.querySelector(attach);
  }

  if (typeof attach === 'function') {
    parent = attach();
  }

  if ((0, _typeof2.default)(attach) === 'object' && attach instanceof window.HTMLElement) {
    parent = attach;
  }

  if (isNoSSR()) return parent || document.body;
  return parent;
}

var Portal = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var attach = props.attach,
      children = props.children;

  var _useMemo = (0, _react.useMemo)(function () {
    var parentDom = getAttach(attach);

    if (parentDom && isNoSSR()) {
      var div = document.createElement('div');
      parentDom.appendChild(div);
      return [parentDom, div];
    }

    return [null, children];
  }, [attach]),
      _useMemo2 = (0, _slicedToArray2.default)(_useMemo, 2),
      parent = _useMemo2[0],
      container = _useMemo2[1];

  (0, _react.useEffect)(function () {
    return function () {
      if (container instanceof window.HTMLElement) container.remove();
    };
  }, []);
  (0, _react.useImperativeHandle)(ref, function () {
    return parent;
  });
  return parent ? /*#__PURE__*/(0, _reactDom.createPortal)(children, container) : container;
});
Portal.displayName = 'Portal';
var _default = Portal;
exports.default = _default;